# -*- coding: utf-8 -*-

from django.contrib.auth.models import User
from django.conf import settings
from django.contrib.auth.views import login
from django.http import HttpResponseRedirect, HttpResponseForbidden
from django.shortcuts import get_object_or_404

class statuser:
    def process_view(self, request, view, args, kwargs):
        try: uid = int(kwargs['statuser'])
        except KeyError:
            # значит функция и не ждёт statuser'a
            request.statuser = None
            return
        if uid == request.user.id:
            request.statuser = request.user
        elif request.user.is_authenticated() and request.user.is_staff:
            request.statuser = get_object_or_404(User, pk=uid)
        else:
            return HttpResponseForbidden(u"Ты можешь смотреть только свою статистику")
        return None


# from djangosnippets

class RequireLoginMiddleware(object):

    def __init__(self):
        self.require_login_path = getattr(settings, 'REQUIRE_LOGIN_PATH', \
            '/accounts/login/')

    def process_request(self, request):
        if request.user.is_anonymous() and \
            not(filter(lambda x: request.path.startswith(x), \
                   settings.ANONYMOUS_AVAILABLE_PAGES)):
            if request.POST:
                return login(request)
            else:
                return HttpResponseRedirect('%s?next=%s' % \
                (self.require_login_path, request.path))
